package com.sinaapp.kltq.dinosaurweather;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.view.GestureDetector;
import android.os.Message;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.os.Handler;

import com.sinaapp.kltq.data.CityListItem;
import com.sinaapp.kltq.data.WeatherDay;
import com.sinaapp.kltq.data.WeatherRealTime;
import com.sinaapp.kltq.weathermanager.WeatherManager;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Implementation of App Widget functionality.
 */
public class WeatherWidget extends AppWidgetProvider {

    private static Timer timer;
    private static Context context;
    private static AppWidgetManager appWidgetManager;
    private static WeatherManager wm;
    private static int cityIndex = 0;
    private static int cityNum;
    private static GestureDetector gestureDetector;
    private static Button button;

    private static final String CHANGE_ACTION = "kltq.widgetActions.Change";
    private static final String REFRESH_ACTION = "kltq.widgetActions.Refresh";



    private static String getCity(int cityIndex) {

        if (wm == null) {
            System.out.println("GET:nullptr");
            return "";
        }

        List<CityListItem> list = wm.getCityList();
        cityNum = list.size();
        for (CityListItem item : list) {
            if (item.cityIndex == cityIndex)
                return item.city;
        }
        return "";
    }

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {


        // There may be multiple widgets active so update all of them
        final int N = appWidgetIds.length;
        this.context = context;
        this.appWidgetManager = appWidgetManager;
        wm = new WeatherManager(context);
        System.out.println("INIT:" + this.toString());
        for (int i = 0; i < N; i++) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    //System.out.println(cityIndex);
                    handler.sendEmptyMessage(0x123);
                }
            }
                    , 0, 7200000);
            //updateAppWidget(context, appWidgetManager, appWidgetIds[i]);
        }
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.weather_widget);
        {
            Intent intent = new Intent();
            //为Intent对象设置Action
            intent.setAction(CHANGE_ACTION);
            //使用getBroadcast方法，得到一个PendingIntent对象，当该对象执行时，会发送一个广播
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                    intent, 0);
            remoteViews.setOnClickPendingIntent(R.id.btnChange, pendingIntent);
        }
        {
            Intent intent = new Intent();
            //为Intent对象设置Action
            intent.setAction(REFRESH_ACTION);
            //使用getBroadcast方法，得到一个PendingIntent对象，当该对象执行时，会发送一个广播
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                    intent, 0);
            remoteViews.setOnClickPendingIntent(R.id.btnRrefresh, pendingIntent);
        }
        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
        super.onEnabled(context);
        System.out.println("ENABLE");
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(CHANGE_ACTION)) {

            if (wm == null) {
                wm = new WeatherManager(context);
                this.context=context;
            }
            //this.context=context;
            cityIndex++;
            if (cityIndex >= cityNum)
                cityIndex = 0;
            System.out.println("RECV:" + this.toString() + "[" + cityIndex + ":" + cityNum + "]");
            handler.sendEmptyMessage(0x123);
        } else if(intent.getAction().equals(REFRESH_ACTION)) {
            handler.sendEmptyMessage(0x123);
        }else{
            super.onReceive(context, intent);
        }
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
        super.onDisabled(context);
        System.out.println("DISABLE");
    }

    private static Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {

                String city = getCity(cityIndex);
                if (city.length() == 0) {
                    return;
                }
                WeatherRealTime realTimeData = wm.getRealTimeWeather(city);
                String wendu;
                String type;
                String high;
                String low;
                String detailWendu;
                String fengxiang;
                String fengli;
                // 获取数据

                WeatherDay dayData = wm.getForecastWeather(city).get(1);
                // 获取更新日
                Date updateDate = wm.getUpdateDate(city);
                if (updateDate == null) {
                    wendu = type = detailWendu = fengxiang = fengli = "N/A";
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                    Date today = new Date(System.currentTimeMillis());
                    // 根据更新日载入数据
                    if (sdf.format(today).compareTo(sdf.format(updateDate)) == 0) {   // 今日更新
                        wendu = "" + realTimeData.wendu;
                        if (today.getHours() > 8 && today.getHours() < 20) {
                            type = dayData.dayType;
                        } else {
                            type = dayData.nightType;
                        }
                        high = dayData.high.substring(3);
                        high = high.substring(0, high.length() - 1);
                        low = dayData.low.substring(3);
                        low = low.substring(0, low.length() - 1);
                        detailWendu = low + "-" + high;
                        fengxiang = realTimeData.fengxiang;
                        fengli = realTimeData.fengli;
                    } else {    // 之前更新
                        // 找到新的dayData
                        dayData = null;
                        for (WeatherDay day : wm.getForecastWeather(city)) {
                            if (day.date.substring(0, 4).compareTo(sdf.format(today)) == 0) {
                                dayData = day;
                            }
                        }
                        // 更新日期过早
                        if (dayData == null) {
                            wendu = type = detailWendu = fengxiang = fengli = "N/A";
                        } else {
                            // 有本地缓存
                            wendu = "N/A";
                            high = dayData.high.substring(3);
                            high = high.substring(0, high.length() - 1);
                            low = dayData.low.substring(3);
                            low = low.substring(0, low.length() - 1);
                            detailWendu = low + "-" + high;
                            if (today.getHours() > 8 && today.getHours() < 20) {
                                type = dayData.dayType;
                                fengxiang = dayData.dayFx;
                                fengli = dayData.dayFl;
                            } else {
                                type = dayData.nightType;
                                fengxiang = dayData.nightFx;
                                fengli = dayData.nightFl;
                            }
                        }
                    }
                }
                //if (context == null)
                //System.out.println("f*ck!");
                RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.weather_widget);

                views.setTextViewText(R.id.widegtCity, city);
                views.setTextViewText(R.id.widegtToday,detailWendu);
                views.setTextViewText(R.id.widegtRealtime, wendu+"°C");
                views.setTextViewText(R.id.widgetWind, fengxiang + " " + fengli);
                int typeImgId = R.drawable.na;
                String typeImg = type;
                boolean tooDark = false;
                if (type.compareTo("雷阵雨") != 0 && type.length() > 2) {
                    typeImg = type.substring(type.length() - 2, type.length());
                }
                if (typeImg.compareTo("晴") == 0) {
                    typeImgId = R.drawable.sunny;
                } else if (typeImg.compareTo("多云") == 0) {
                    typeImgId = R.drawable.cloud;
                } else if (typeImg.compareTo("大雨") == 0 || type.compareTo("中雨") == 0 || type.compareTo("小雨") == 0) {
                    typeImgId = R.drawable.rain;
                } else if (typeImg.compareTo("阵雨") == 0) {
                    typeImgId = R.drawable.shower;
                } else if (typeImg.compareTo("雷阵雨") == 0) {
                    typeImgId = R.drawable.thundershower;
                    // 需要设置颜色
                    tooDark = true;
                } else if (typeImg.compareTo("暴雨") == 0) {
                    typeImgId = R.drawable.storm;
                    // 需要设置颜色
                    tooDark = true;
                } else if (typeImg.compareTo("雪") == 0) {
                    typeImgId = R.drawable.snow;
                } else if (typeImg.compareTo("晴转多云") == 0) {
                    typeImgId = R.drawable.sunny2cloud;
                }
                views.setImageViewResource(R.id.widget_image,typeImgId);
                ComponentName componentName = new ComponentName(context, WeatherWidget.class);
                if(appWidgetManager==null){
                    appWidgetManager=AppWidgetManager.getInstance(context);
                }
                appWidgetManager.updateAppWidget(componentName, views);
            }
            super.handleMessage(msg);
        }
    };

    private class Guest extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            System.out.print(2);
            return true;
        }

        @Override
        public void onShowPress(MotionEvent e) {
            System.out.print(2);
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            System.out.print(2);
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            System.out.print(2);
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }
    }

}

